package leetCode;

public class t142 {
    public static void main(String[] args) {
        ListNode n1=new ListNode(3,null);
        ListNode n2=new ListNode(2,null);
        ListNode n3=new ListNode(0,null);
        ListNode n4=new ListNode(-4,null);
        n1.next=n2;
        n2.next=n3;
        n3.next=n4;
        n4.next=n2;
        new Solution142().detectCycle(n1);
    }

}
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
 class Solution142 {
    public ListNode detectCycle(ListNode head) {
        if (head==null){
            return head;
        }
        ListNode fastNode=head.next;
        ListNode slowNode=head;
        while (slowNode!=null&&fastNode!=null&&slowNode!=fastNode){
            slowNode=slowNode.next;
            if (fastNode.next==null){
                return null;
            }
            fastNode=fastNode.next.next;
        }
        if (fastNode==null){
            return null;
        }
        ListNode index1=head;
        ListNode index2=fastNode.next;
        while (index1!=index2){
            index1=index1.next;
            index2=index2.next;
        }
        return index2;
    }
}
